package com.example.demo.filter;

import com.example.demo.utils.JwtUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;


@Log4j2
//过滤除login以外的接口
@WebFilter(urlPatterns = "/*")
public class JwtFilter implements Filter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            filterChain.doFilter(request,response);
            return;
        }

        String requestURI = request.getRequestURI();
        log.warn(requestURI);
        if(requestURI.contains("/user/login")){
            filterChain.doFilter(request,response);
            return;
        }


        if(requestURI.contains("/user/refresh-token")){
            try {
//            获取RequestBody中的refreshToken参数
                String refreshToken = request.getParameter("refreshToken");
                // 校验 refreshToken
                JwtUtils.parseToken(refreshToken);
                filterChain.doFilter(request,response);
                return;
            }catch (Exception e){
                jwtUtils.sendErrorResponse(response,401,"refreshToken无效");
                return;
            }
        }

        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            jwtUtils.sendErrorResponse(response,401,"token不存在");
            return;
        }

        try{
//            校验token
            JwtUtils.parseToken(token);
        }catch (Exception e){
            System.out.println(e)       ;
            jwtUtils.sendErrorResponse(response,401,"token无效");
            return;
        }
        filterChain.doFilter(request,response);
    }
}
